package com.dgshanger.sanhxiaofeisc.ui.home.activity

import android.content.Intent
import android.graphics.Point
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import com.blankj.utilcode.util.EncryptUtils
import com.dgshanger.sanhxiaofeisc.R
import com.dgshanger.sanhxiaofeisc.common.Constants
import com.dgshanger.sanhxiaofeisc.mvp.contract.PayCodeContract
import com.dgshanger.sanhxiaofeisc.mvp.presenter.PayCodePresenter
import com.dgshanger.sanhxiaofeisc.ui.home.utils.AscIIUtils
import com.dgshanger.sanhxiaofeisc.ui.home.zxing.BarcodeCreater
import com.dgshanger.sanhxiaofeisc.ui.person.purse.PurseActivity
import com.github.yoojia.qrcode.qrcode.QRCodeEncoder
import com.xx.baseuilibrary.mvp.BaseMvpActivity
import com.xx.baseutilslibrary.network.rx.RxHelper
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.bean.ZxingConfig
import com.yzq.zxinglibrary.common.Constant
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_pay_code.*
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * Created by JacobHHH on 2018/4/22.
 * 首页二维码
 */
class PayCodeActivity : BaseMvpActivity<PayCodeContract.Model,PayCodeContract.View,PayCodePresenter>(),PayCodeContract.View, View.OnClickListener {

    private lateinit var mTimer : Timer
    private var mSize : Int =0

    override fun createPresenter(): PayCodePresenter = PayCodePresenter()

    override fun getActivityLayoutId(): Int = R.layout.activity_pay_code

    override fun initData() {
        initView()
    }

    private fun initView() {
        tv_title.text=Constants.getUserEntity().vip_name
        tv_instructions.setOnClickListener(this)
        tv_pay_setting.setOnClickListener(this)
        tv_check_wallet.setOnClickListener(this)
        tv_refresh_code.setOnClickListener(this)
        tv_scan.setOnClickListener(this)

        val manager = getSystemService(WINDOW_SERVICE) as WindowManager
        val display = manager.defaultDisplay
        val displaySize = Point()
        display.getSize(displaySize)
        mSize = Math.min(displaySize.x, displaySize.y)

        refreshCode()
    }

    override fun initEvent() {

    }

    override fun onClick(view: View?) {
        when(view!!.id){
            R.id.tv_instructions->{//使用说明
                val intent = Intent(mContext, PayInstructionsActivity::class.java)
                startActivity(intent)
            }
            R.id.tv_pay_setting->{//付款方式设置
                val intent = Intent(mContext, CodePaySettingActivity::class.java)
                startActivity(intent)
            }
            R.id.tv_check_wallet->{//查看钱包
                val intent = Intent(mContext, PurseActivity::class.java)
                startActivity(intent)
            }
            R.id.tv_scan->{ //扫一扫
                initZXing()
            }
            R.id.tv_refresh_code-> {//刷新二维码
                val otp = EncryptUtils.encryptSHA1ToString(Constants.getPayToken() +((System.currentTimeMillis()/1000).toInt()).toString()).toLowerCase()
                val phone=Constants.getUserEntity().mobile
                val mysteriousNum=Constants.getMysteriousNum()
                val ascII = AscIIUtils.stringToAscii(otp).substring(6, 13)
                val codeNum = (phone.toLong() * mysteriousNum.toLong() + ascII.toInt()).toString()
                //条形码
                BarcodeCreater.getOneCode(mContext, iv_bar_code,codeNum)
                //二维码
                generateQRCode(mSize,iv_code,codeNum)

                tv_code_num.text=codeNum
            }
        }
    }

    private fun initZXing() {
       /* //val integrator = IntentIntegrator.forSupportFragment(this);//v4包Fragment
        //IntentIntegrator integrator = IntentIntegrator.forFragment(HomeFragment.this);//app包Fragment
        var integrator = IntentIntegrator(this)//activity
        // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
        integrator.captureActivity = ScanActivity::class.java
        //integrator.setPrompt("请将二维码置于扫描框") //底部的提示文字，设为""可以置空
        integrator.setCameraId(0) //前置或者后置摄像头
        integrator.setBeepEnabled(true) //扫描成功的「哔哔」声，默认开启
        integrator.setBarcodeImageEnabled(true)
        integrator.initiateScan()*/
        val intent = Intent(mContext, CaptureActivity::class.java)
        val zxingConfig = ZxingConfig()
        zxingConfig.setPlayBeep(true)
        zxingConfig.setShake(true)
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, zxingConfig)
        startActivityForResult(intent, REQUEST_CODE_SCAN)
    }

    private var REQUEST_CODE_SCAN : Int=10003
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN) {
            if (data != null) {
                var content = data.getStringExtra(Constant.CODED_CONTENT)
                val intent = Intent(mContext, PaymentCodeActivity::class.java)
                intent.putExtra("shop_number", content)
                startActivity(intent)
            }else{
                showToast("未能识别")
            }
        }
    }

    /**
     * 每个1分钟刷新一次二维码
     */
    private lateinit var mDisposable : Disposable
    private lateinit var mContent : String
    private fun refreshCode(){
        Observable.interval(0,60,TimeUnit.SECONDS)
                .doOnSubscribe({
                    mDisposable=it
                })
                .map {

                    val otp = EncryptUtils.encryptSHA1ToString(Constants.getPayToken() +((System.currentTimeMillis()/1000).toInt()).toString()).toLowerCase()
                    val phone=Constants.getUserEntity().mobile
                    val mysteriousNum=Constants.getMysteriousNum()
                    val ascII = AscIIUtils.stringToAscii(otp).substring(6, 13)
                    mContent =(phone.toLong() * mysteriousNum.toLong() +ascII.toInt()).toString()
                    QRCodeEncoder.Builder()
                            .width(mSize)
                            .height(mSize)
                            .paddingPx(0)
                            .marginPt(0)
                            .centerImage(mContext,R.drawable.logo_xi_)
                            .build()
                            .encode(mContent)

                }.compose(RxHelper.io_main())
                .subscribe({
                    //条形码
                    BarcodeCreater.getOneCode(mContext, iv_bar_code,mContent)
                    //二维码
                    iv_code.setImageBitmap(it)
                    tv_code_num.text=mContent
                })
    }

    override fun onDestroy() {
        super.onDestroy()
        mDisposable.dispose()//取消定时器
    }

    //二维码
    private fun generateQRCode(size: Int, imageView: ImageView, content : String) {
        val bitmap = QRCodeEncoder.Builder()
                .width(size)
                .height(size)
                .paddingPx(0)
                .marginPt(0)
                .centerImage(mContext,R.drawable.logo_xi_)
                .build()
                .encode(content)

        imageView.setImageBitmap(bitmap)
    }



}